package jwcb.hire.common.security.filter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jwcb.hire.common.core.utils.StringUtil;
import jwcb.hire.common.core.utils.ThreadLocalUtil;
import jwcb.hire.common.domain.constants.SecurityConstants;
import jwcb.hire.common.domain.domain.ResultCode;
import jwcb.hire.common.domain.exception.ServiceException;
import jwcb.hire.common.domain.domain.dto.LoginUserDto;
import jwcb.hire.common.security.service.TokenService;
import jwcb.hire.common.security.utils.SecurityUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * 用户身份认证拦截器
 */
@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {


    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        String token = SecurityUtil.getToken(request);
        if(StringUtil.isBlank(token)) {
            return true;
        }
        LoginUserDto loginUserDto = tokenService.getLoginUserDto(token);
        if(loginUserDto.getExpireTime() < System.currentTimeMillis()) {
            // 已经过期
            tokenService.removeLoginStatus(token);
            throw new ServiceException(ResultCode.LOGIN_STATUS_OVERTIME);
        }
        Long userId = loginUserDto.getUserId();

        Integer userIdentity = loginUserDto.getUserIdentity();
        ThreadLocalUtil.set(SecurityConstants.USER_ID, userId);
        ThreadLocalUtil.set(SecurityConstants.USER_IDENTITY,userIdentity);
        // 延长token过期时间
        tokenService.extendToken(loginUserDto);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request,
                                HttpServletResponse response,
                                Object handler,
                                Exception ex) {
        ThreadLocalUtil.remove();
    }

}
